<?php

namespace WebApp\server;

use ErrorException;
use FilesystemIterator;
use Redis;
use Swoole\WebSocket\Server;

class ServerCreator {
    private static $redisClient;
    private static $extension = [];

    /**
     * @var Server
     */
    public static $server = null;

    /**
     * @return Redis
     */
    public static function getRedisClient(){
        return self::$redisClient;
    }

    public static function createServer(&$server = null){
//        self::initData();
        if($server){
            self::$server = $server;
        }
        self::changeUser();
        date_default_timezone_set('Asia/Shanghai');
        unset($server);
    }

    private static function initData(){
        try{
            self::$redisClient = new Redis();
            self::$redisClient->connect('111.231.12.232', 443);
        }catch (ErrorException $e){
            var_dump($e->getMessage());
        }
    }

    private static function includeDir()
    {
        $dirArr = [ ROOT_DIR.'app/model/',ROOT_DIR.'app/controller/'];
        foreach($dirArr as $dir)
            self::includeFile($dir);
    }

    private static function changeUser()
    {
        //脱离父进程
        $user = posix_getpwnam('ljm');
        posix_setuid($user['uid']);
        posix_setgid($user['gid']);
    }

    private static function includeFile($dir)
    {
        $fileIterator = new FilesystemIterator($dir);
        foreach($fileIterator as $fileInfo){
            if(!$fileInfo->isDir()){
                require_once($dir.$fileInfo->getFileName().'');
            }else{
                self::includeFile($dir.$fileInfo->getFileName().'/');
            }
        }
    }
    public static function autoLoad($class)
    {
        $package = substr($class,0,strpos($class,'\\'));
        if(array_search($package, self::$extension) !== false){
            $class = 'extensions\\' .$class;
            var_dump($class);
        }
        $filePath = ROOT_DIR . str_replace('\\','/',$class) . ".php";
        if (is_file($filePath)) {
            require_once($filePath . "");
        } else {
            throwError("没有找到该类：" . $filePath);
        }
    }
}